//
//  StockAppHelper.m
//  Stock
//
//  Created by blacksun on 11-6-23.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "StockAppHelper.h"


@implementation StockAppHelper


-(void)createTables{
    sqlite3 *database = [[SQLiteInstanceManager sharedManager] database];
    NSString *createSql1 = @"CREATE TABLE IF NOT EXISTS STOCK_NEWS(PK integer primary key,REPORT_ID TEXT,SECTION_ID TEXT,SECTION_INDEX INTEGER,PUB_DATE TEXT,AUTHOR TEXT,SOURCE TEXT,TITLE TEXT)";
	char *errorMsg1;
    if (sqlite3_exec(database, [createSql1 UTF8String], NULL, NULL, &errorMsg1) != SQLITE_OK) {
		sqlite3_close(database);
	}
	[createSql1 release];
    
	char *errorMsg2;
	NSString *createSql2 = @"CREATE TABLE IF NOT EXISTS MY_STOCK_NEWS(PK integer primary key,REPORT_ID TEXT,SECTION_ID TEXT,SECTION_INDEX INTEGER,PUB_DATE TEXT,AUTHOR TEXT,SOURCE TEXT,TITLE TEXT,STOCK_ID TEXT)";
	if (sqlite3_exec(database, [createSql2 UTF8String], NULL, NULL, &errorMsg2) != SQLITE_OK) {
		sqlite3_close(database);
	}
	[createSql2 release];
}



-(NSArray *)buildStockChildSegmentItemImageWithTitles:(NSArray *)theTitles{
    //UIImage *backgroundImage = [UIImage imageNamed:@"segment_bg.png"];
    NSMutableArray *segmentImages = [NSMutableArray array];
    CommonUtil *commonUtil = [CommonUtil shareInstance];
    for (NSString *title in theTitles) {
        StockChildSegmentItemController *segmentItemControoler = [[StockChildSegmentItemController alloc] initWithNibName:@"StockChildSegmentItemController" bundle:nil];
        segmentItemControoler.segmentItemText = title;
        [segmentImages addObject:[commonUtil buildImageWithView:segmentItemControoler.view]];
        [segmentItemControoler release];
    }
    return segmentImages;
}

-(UIView *)getTableFooterView{
    UIView *footerView = [[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 44.0)] autorelease];
    footerView.backgroundColor = [UIColor blackColor];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:footerView.frame];
    imageView.image = [UIImage imageNamed:@"cellbg2.png"];
    [footerView addSubview:imageView];
    [imageView release];
    
    UIActivityIndicatorView *activeView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    [activeView startAnimating];
    activeView.hidden = NO;
    CGRect frame = activeView.frame;
    activeView.frame = CGRectMake(100.0, 12.0, frame.size.width, frame.size.height);
    [footerView addSubview:activeView];
    [activeView release];
    
    UILabel *loadingLabel = [[UILabel alloc] initWithFrame:CGRectMake(120.0, 7.0, 100.0, 30.0)];
    loadingLabel.textColor = [UIColor whiteColor];
    loadingLabel.backgroundColor = [UIColor clearColor];
    loadingLabel.text = @"正在加载...";
    [footerView addSubview:loadingLabel];
    [loadingLabel release];
    return footerView;
}
-(UIView *)setupLoadingViewWithFrame:(CGRect)frame{
    float x = frame.origin.x;
    if (x>320.0 || x<0.0) {
        x=0.0;
    }
    UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(x,frame.origin.y , frame.size.width, frame.size.height)] autorelease];
    view.backgroundColor = [UIColor whiteColor];
    view.alpha = 0.3;
    UIActivityIndicatorView *activeView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    
    activeView.frame = CGRectMake((frame.size.width-37.0)/2, (frame.size.height-37.0)/2, 37.0, 37.0);
    activeView.hidden = NO;
    [activeView startAnimating];
    [view addSubview:activeView];
    [activeView release];
    
    return view;
}
-(UIView *)setupLoadMoreViewWithTarget:(id)target andAction:(SEL)action{
    
    UIView *footerView = [[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 44.0)] autorelease];
    footerView.backgroundColor = [UIColor blackColor];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:footerView.frame];
    imageView.image = [UIImage imageNamed:@"cellbg2.png"];
    [footerView addSubview:imageView];
    [imageView release];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(80.0, 2.0, 160.0, 40.0);
    [button setTitle:@"加载更多..." forState:UIControlStateNormal];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:button];
    
    return footerView;
}

-(UIView *)setupPopupViewWithMessage:(NSString *)message{
    CGSize constraint = CGSizeMake(180.0, 20000.0);
    CGSize size = [message sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
    float width = 120.0;
    float heigth = 80.0;
    float x = 110.0;
    float y = 150.0;
    UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(x, y, width, heigth)] autorelease];
    view.backgroundColor = [UIColor whiteColor];
    view.layer.cornerRadius = 5.0;
    view.layer.masksToBounds = YES;
    UIView *blackView = [[UIView alloc] initWithFrame:CGRectMake(1.0, 1.0, 118.0, 78.0)];
    blackView.backgroundColor = [UIColor blackColor];
    blackView.layer.cornerRadius = 5.0;
    blackView.layer.masksToBounds = YES;
    [view addSubview:blackView];
    [blackView release];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30.0, 30.0, size.width, size.height)];
    label.textColor = [UIColor whiteColor];
    label.backgroundColor = [UIColor clearColor];
    label.numberOfLines = 0;
    label.lineBreakMode = UILineBreakModeWordWrap;
    label.text = message;
    
    [view addSubview:label];
    [label release];
    return view;
}
-(BOOL)canAddFavoriteStock{
    if (IsPaidVersion) {
        return YES;
    }
    if([[MyStock allObjects] count]<=MaxFavoriteStockCount){
        return YES;
    }
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"您使用的是免费版，最多只能添加%d个自选股",MaxFavoriteStockCount+1] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"升级到专业版",nil];
    
    [alertView show];
    [alertView release];
    return NO;
}
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex==1) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:ProVersionAppStoreLink]];
    }
}

-(void)setupAddFavoriteNotify{
    UIView *notifyView = [self setupPopupViewWithMessage:@"添加成功"];
    notifyView.alpha = 0.3;
    StockAppDelegate *delegate = [UIApplication sharedApplication].delegate;
    [delegate.navigationController.topViewController.view addSubview:notifyView];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.8];
    notifyView.alpha = 1.0;
    [UIView commitAnimations];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDelay:1.0];
    [UIView setAnimationDuration:0.8];
    notifyView.alpha = 0.0;
    [UIView commitAnimations];
    
    [notifyView performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:1.8];
}

-(void)showAlertViewWithMessage:(NSString *)message{
    [self showAlertViewWithMessage:message andDelegate:nil];
}
-(void)showAlertViewWithMessage:(NSString *)message andDelegate:(id)aDelegate{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:aDelegate cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alertView.delegate = aDelegate;
    [alertView show];
}

//单例实现
static StockAppHelper *instance = nil;
+(id)shareInstance{
    @synchronized(self){
        if (instance == nil) {
            instance = [[self alloc] init];
        }
    }
    return instance;
}
+ (id)allocWithZone:(NSZone *)zone{
    @synchronized(self) {
        if (instance == nil) {
            instance = [super allocWithZone:zone];
            return instance;  // assignment and return on first allocation
        }
    }
    
    return nil; //on subsequent allocation attempts return nil
}

- (id)copyWithZone:(NSZone *)zone{
    return self;
}

- (id)retain{
    return self;
}

- (unsigned)retainCount{
    return UINT_MAX;  //denotes an object that cannot be released
}

- (void)release{
    //do nothing
}

- (id)autorelease{
    return self;
}
@end
